//
//  ShopAdvertisingViewController.swift
//  iModern
//
//  Created by Ralf on 8/11/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class ShopAdvertisingViewController: TableViewController, UIActionSheetDelegate
{
    var articles    = NSMutableArray()
    var appointment = NSMutableArray()
    var max:    Int = 10
    var offset: Int = 0
    var end         = false
    var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    var articleManager = ArticleManager()

    var advertisingManager = AdvertisingManager()

    var quanData = NSMutableDictionary()

    var segmentedControl: UISegmentedControl?
    var number      = 3
    var minusNumber = 0
    var indexNumber:      Int!
    var midNumber   = 0
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.navigationItem.title = "商品管理"
        self.initBackButton()
        self.tableView.registerNib(UINib(nibName: "ShopAdvertisingViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ShopAdvertising")

        if segmentedControl == nil
        {
            let view1 = UIView()
            view1.frame = CGRectMake(0, 10, 180, 50)
            view1.backgroundColor = UIColor.groupTableViewBackgroundColor()
            self.tableView!.tableHeaderView = view1
            
            let screen = UIScreen.mainScreen().bounds
            segmentedControl = UISegmentedControl(items: ["上架", "下架"])
            segmentedControl!.tintColor = Theme.theme_color
            segmentedControl?.frame = CGRectMake((screen.size.width - 180) / 2, 10, 180, 28)
            segmentedControl!.selectedSegmentIndex = 0
            segmentedControl!.addTarget(self, action: "segmentSelected:", forControlEvents: .ValueChanged)
//            self.navigationItem.titleView = segmentedControl
            view1.addSubview(segmentedControl!)
        }

        loadData()
    }

    func loadData()
    {
        if (end)
        {
            return;
        }

        if (appDelegate.isLogged())
        {
            var rs: ResultSet?

            if segmentedControl?.selectedSegmentIndex == 0
            {
                self.tableView.userInteractionEnabled=true
                rs = articleManager.queryMyAdvertising(max, offset: offset, status: "Ready for Sale")
            }
            else
            {
                rs = articleManager.queryMyAdvertising(max, offset: offset, status: "Disable")
                self.tableView.userInteractionEnabled=true

            }

            if (self.verifyResutSet(rs))
            {
                if (rs!.isEmpty())
                {
                    end = true
                }
                else
                {
                    articles.addObjectsFromArray(rs!.toMutableArray() as [AnyObject])

                    offset = articles.count
                }
            }
        }

        self.tableView.reloadData()
    }

    @IBAction override func reloadData(sender: AnyObject?)
    {
        offset = 0
        end = false
        articles.removeAllObjects()
        self.loadData()
        super.reloadData(sender)
    }

    func segmentSelected(sender: UISegmentedControl)
    {
        reloadData(sender)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()

    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {

        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {

        return articles.count
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return 120
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

//        var cell: UITableViewCell!
        let cell = tableView.dequeueReusableCellWithIdentifier("ShopAdvertising", forIndexPath: indexPath) as! ShopAdvertisingViewCell

        quanData = articles[indexPath.row] as! NSMutableDictionary
        cell.setData(quanData)
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        indexNumber = indexPath.row
        var btntext :String?
        if segmentedControl?.selectedSegmentIndex == 0
        {
            btntext = "下架"
        }
        else
        {
            btntext = "上架"
        }
        
        let alertContorller = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let alertCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        let alertA = UIAlertAction(title: "查看", style: UIAlertActionStyle.Default) {
            (action: UIAlertAction!) -> Void in
            self.viewProd()
        }
        let alertB = UIAlertAction(title: btntext!, style: UIAlertActionStyle.Default) {
            (action: UIAlertAction!) -> Void in
            self.changeStateProd()
        }
        let alertC = UIAlertAction(title: "编辑", style: UIAlertActionStyle.Default){
            (action:UIAlertAction!) -> Void in
            self.editProd()
        }
        alertContorller.addAction(alertCancel)
        alertContorller.addAction(alertA)
        alertContorller.addAction(alertB)
        alertContorller.addAction(alertC)
        self.presentViewController(alertContorller, animated: true, completion: nil)
    }

    func viewProd()
    {
        let controller = AdvertisingPageViewController()
        let data = articles[indexNumber] as! NSMutableDictionary
        controller.activity = data
        self.pushViewController(controller)
    }
    
    func changeStateProd()
    {
        let data                = articles[indexNumber] as! NSMutableDictionary
        let article             = data["article"] as! NSDictionary
        let id:      AnyObject! = article["id"]
        let strVar1: String     = String(stringInterpolationSegment: id)
        
        var rs : ResultSet?
        
        if segmentedControl?.selectedSegmentIndex == 0
        {
            rs = advertisingManager.disableAdvertising(strVar1)
        }
        else
        {
            rs = advertisingManager.enableAdvertising(strVar1)
        }
        
        if rs == nil
        {
            self.alertNetworkConnectionException()
        }
        
        if rs!.hasErrors()
        {
            if rs!.errorCode == 3020
            {
                alertUserStatusException()
                NSNotificationCenter.defaultCenter().postNotificationName("Logout", object: nil)
                self.view.endEditing(true)
                navigationController?.popToRootViewControllerAnimated(true)
            }
            alertErrorMessage(rs!.errorMessage)
        }
        self.view.endEditing(true)
        appDelegate.contactManager.loadContact()
        //            self.navigationController?.popViewControllerAnimated(true)
        
        reloadData("0")
        self.tableView.reloadData()
        NSNotificationCenter.defaultCenter().postNotificationName("Refresh Market", object: nil)
    }
    
    func editProd()
    {
        let vc   = ShopAdvertisingFormViewController()
        let data = articles[indexNumber] as! NSMutableDictionary
        
        vc.quanData2 = data
        self.navigationController?.pushViewController(vc, animated: true)

    }
}
